<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\BusinessDistrict;
use app\common\model\BusinessDistrictAdmin;
use app\common\model\DistrictShopCategoryModel;
use app\common\model\PointsLog;
use app\common\model\ShopManage;
use app\common\model\Shop;
use think\facade\Db;
use think\Validate;

class District extends BaseController
{

    /**
     * 商圈搜索
     * 0901
     */
    public function districtSearch()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'key_words|关键词' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $data = BusinessDistrict::where('name', 'like', '%' . $param['key_words'] . '%')->select();
        return success($data);
    }

    /**
     * 商圈列表
     * 0816  超管在管理管理员时,可以选择给某个商圈新增管理员
     * 需要获取当前有管理权限的所有商圈列表
     */
    public function districtList()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'flag|用途' => 'require|in:1,3,4',  //1:商圈管理  3:店铺管理 4:管理员管理
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $type         = input('type', 0);
        $userId       = $this->request->uid;
        $re           = BusinessDistrictAdmin::where('user_id', $userId)->where('status', 1)->select();
        $districtList = [];
        if ($re) {
            $districtArr = [];
            $flag        = $param['flag'];
            foreach ($re as $k => $v) {
                if (in_array($flag, explode(',', $v->function_arr))) {  //1:商圈管理  3:店铺管理 4:管理员管理
                    $districtArr[] = $v->district_id;
                }
            }
            if ($districtArr) {
                $districtList = BusinessDistrictAdmin::alias('da')
                    ->join('pm_business_district d', 'da.district_id = d.id', 'right')
                    ->where('da.district_id', 'in', $districtArr)
                    ->where('da.user_id', $userId)
                    ->where('d.type', $type)
                    ->field('d.id,d.name,d.logo')
                    ->select();
            }
        }
        return success($districtList);
    }

    /**
     * 商圈详情
     * 0823
     * 商圈首页调用接口 获取展示信息
     */
    public function districtDetail()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_id' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId     = $this->request->uid;
        $districtId = $param['district_id'];
        //搜索这个商圈或者连锁店
        $districtInfo = BusinessDistrict::find($districtId);
        if (!$districtInfo) {
            return error('商圈或连锁信息不存在');
        }
        //获取图片
        $out['image'] = $districtInfo->image;
        //获取提示语
        $out['tip'] = $districtInfo->tip;
        //商圈标题
        $out['title'] = $districtInfo->title;
        //获取当前用户可用积分
        //获取商圈中所有店铺id
        $shopIdList = Shop::where('district_id', $districtId)->column('id');
        $num        = 0;
        if ($shopIdList) {
            $num = (new PointsLog())->getUsefulPoints($userId, $shopIdList);
        }
        $out['point'] = $num;
        //获取图标
        $host               = $this->request->domain();
        $out['icon_status'] = 1;
        $out['icon']        = [
            [
                'img'  => $host . '/mini/homeicon3.png',
                'name' => '活动',
            ],
            [
                'img'  => $host . '/mini/homeicon4.png',
                'name' => '游戏',
            ],
            [
                'img'  => $host . '/mini/shangguan.png',
                'name' => '合作方',
            ],
            [
                'img'  => $host . '/mini/homeicon2.png',
                'name' => '收藏',
            ],
        ];
        //获取商圈 店铺分类
        $out['shop_category'] = DistrictShopCategoryModel::where('district_id', $districtId)->order('sort', 'desc')->field('id,name')->select();
        return success($out);
    }

    /**
     * 获取商圈店铺分类下的店铺信息
     * 0823
     *
     */
    public function districtShopList()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'category_id|商圈店铺分类id' => 'require', //商圈店铺分类id
            'district_id|商圈id'     => 'require', //商圈id
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        [$pageSize, $page] = paginate($param);
        $districtId = $param['district_id'];
        //获取商圈/连锁店信息
        $districtInfo = BusinessDistrict::find($districtId);
        if (!$districtInfo) {
            return error('商圈/连锁信息异常');
        }
        $categoryId = $param['category_id'];
        if ($categoryId == 0) {
            $shopList = Shop::where('district_id', $districtId)
                ->field('id,logo,name,phone,address')
                ->limit($pageSize * $page, $pageSize)
//                ->order('sort','desc')
                ->select();
        } else {
            //获取店铺分类
            $re = DistrictShopCategoryModel::find($categoryId);
            if (!$re) {
                return error('分类信息异常');
            }

            //获取店铺idList
            if (!$re->shop_list) {
                return success([]);
            }
            $shopList = explode(',', $re->shop_list);
            $shopList = Shop::where('id', 'in', $shopList)
                ->where('district_id', $re->district_id)
                ->field('id,logo,name,phone,address')
                ->limit($pageSize * $page, $pageSize)
//                ->order('sort','desc')
                ->select();
        }
        foreach ($shopList as &$v) {
            $v->district_name = $districtInfo->name;
            $v->district_log  = $districtInfo->logo;
        }
        return success($shopList);
    }


    /**
     * 当前用户商圈信息
     */
    public function districtMeInfo()
    {
        $userInfo = $this->request->user_info;
        $admin    = BusinessDistrictAdmin::with('district')
            ->alias('da')
            ->join('pm_business_district d', 'da.district_id = d.id', 'right')
            ->where('d.type', 0)
            ->where('da.user_id', $userInfo->id)
            ->field('da.*')
            ->find();

        switch ($admin->role) {
            case 1:
                $admin->role_name = '场所所有人';
                break;
            case 2:
                $admin->role_name = '管理员';
                break;
            case 3:
                $admin->role_name = '工作人员';
                break;
            default:
                $admin->role_name = '异常';
                break;
        }
        $data = ['user_info' => $userInfo, 'district_info' => $admin];
        return success($data);
    }

    /**
     * 商圈管理员列表
     * 0816 修正
     * 根据商圈和用户关联表进行获取所有商圈相关人员信息
     */
    public function adminList()
    {
        $param = $this->request->param();
        list($pageSize, $page) = paginate($param);
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId);
        if (input('district_id', 0)) {
            $re = $re->where('district_id', input('district_id'));
        }
        $re = $re->select();
        if (!$re) {
            return error('当前用户没有权限');
        }
        $districtArr = [];
        foreach ($re as $k => $v) {
            if (in_array(4, explode(',', $v->function_arr))) {
                $districtArr[] = $v->district_id;
            }
        }
        $adminList = [];
        if ($districtArr) {
            $adminList = BusinessDistrictAdmin::with(['user', 'district'])
                ->where('district_id', 'in', $districtArr)
                ->where('role', '>', 1)
                ->where('user_id', '<>', $userId)
                ->order('status', 'desc')
                ->limit($pageSize * $page, $pageSize)
                ->select();
            foreach ($adminList as &$v) {
                switch ($v->role) {
                    case 1:
                        $v->role_name = '场所所有人';
                        break;
                    case 2:
                        $v->role_name = '管理员';
                        break;
                    case 3:
                        $v->role_name = '工作人员';
                        break;
                    default:
                        $v->role_name = '异常';
                        break;
                }
            }
        }
        return success($adminList);
    }

    /**
     * 商圈管理员添加
     * 0816 修正
     * 有权限的管理人 添加 用户成为 商圈管理员
     *
     */
    public function adminAdd()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_id|商圈id' => 'require',
            'phone|手机号'        => 'require|mobile',
            'role|角色'          => 'require|number',
            'function_arr|功能'  => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $districtId = $param['district_id'];
        //判断用户是否有权限进行操作
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $districtId)->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '4')) {
            return error('当前用户权限不足');
        }

        //先行判断用户 是否存在 并且 不在其他商圈中
        $user = \app\common\model\User::where('phone', $param['phone'])->find();
        if (!$user) {
            return error('当前用户不存在');
        }
        $re1 = BusinessDistrictAdmin::where('user_id', $user->id)->find();
        if ($re1) {
            return error('当前用户已在其他商圈中');
        }
        //判断添加的权限 是否 在可授权范围内
        $arr  = explode(',', $param['function_arr']);
        $arr1 = explode(',', $re->function_arr);
        foreach ($arr as $value) {
            if (!in_array($value, $arr1)) {
                return error('当前管理员不能给用户设置超出本身权限');
            }
        }
        //添加用户商圈信息
        BusinessDistrictAdmin::create([
            'district_id'  => $districtId,
            'user_id'      => $user->id,
            'role'         => $param['role'],
            'function_arr' => $param['function_arr']
        ]);
        return success([], '添加成功');
    }


    /**
     * 商圈管理员编辑
     * 0816 修正
     * 有权限的管理人 修改  商圈管理员
     *
     */
    public function adminEdit()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_admin_id|商圈管理员id' => 'require',
            'district_id|商圈id'          => 'require',
            'role|角色'                   => 'require|number',
            'function_arr|功能'           => 'require',
            'status|状态'                 => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $districtId = $param['district_id'];
        //判断用户是否有权限进行操作
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $districtId)->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '4')) {
            return error('当前用户权限不足');
        }

        $re1 = BusinessDistrictAdmin::find($param['district_admin_id']);
        if (!$re1) {
            return error('当前用户信息不存在');
        }

        //判断添加的权限 是否 在可授权范围内
        $arr  = explode(',', $param['function_arr']);
        $arr1 = explode(',', $re->function_arr);
        foreach ($arr as $value) {
            if (!in_array($value, $arr1)) {
                return error('当前管理员不能给用户设置超出本身权限');
            }
        }
        $re1->district_id  = $districtId;
        $re1->role         = $param['role'];
        $re1->function_arr = $param['function_arr'];
        $re1->status       = $param['status'];
        $re1->save();
        return success($re, '修改成功');
    }


    /**
     * 商圈管理员删除
     * 0816 修正
     */
    public function adminDelete()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'admin_id|管理员id' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //查询管理员信息
        $re1 = BusinessDistrictAdmin::find($param['admin_id']);
        if (!$re1) {
            return error('管理员信息不存在');
        }

        //判断用户是否有权限进行操作
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $re1->district_id)->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '4')) {
            return error('当前用户权限不足');
        }
        $re1->delete();
        return success('删除成功');
    }

    /**
     * 商圈工作人员  退出当前商圈
     * 0824
     */
    public function districtExit()
    {
        //获取用户信息
        $userId = $this->request->uid;
        //查询当前用户所属商圈/连锁信息
        $districtAdmin = BusinessDistrictAdmin::alias('da')
            ->join('pm_business_district d', 'da.district_id = d.id', 'right')
            ->where('da.user_id', $userId)
            ->where('d.type', 0) //商圈
            ->field('da.*')
            ->find();
        if (!$districtAdmin) {
            return error('当前用户没有操作权限');
        }
        //判断用户是否能够退出  必须在商圈  必须不是场所所有人
        if ($districtAdmin->role == 1) {
            return error('当前用户是场所持有人,不能退出');
        }
        //退出商圈
        BusinessDistrictAdmin::where('id', $districtAdmin->id)->update(['delete_time' => time()]);
        return success([], '退出成功');
    }

    /**
     * 商圈店铺列表
     * 0817 修正
     * 获取商圈中所有的店铺
     */
    public function shopList()
    {
        $param = $this->request->param();
        list($pageSize, $page) = paginate($param);
        $userId = $this->request->uid;
        //type 判断 商圈 还是 连锁
        $type = input('type', 0);
        $re   = BusinessDistrictAdmin::alias('da')
            ->join('pm_business_district d', 'da.district_id = d.id', 'right')
            ->where('d.type', $type)
            ->where('da.user_id', $userId)->where('da.status', 1);
        if (input('district_id', 0)) {
            $re = $re->where('da.district_id', input('district_id'));
        }
        $re = $re->select();
        if (!$re) {
            return error('当前用户没有权限');
        }
        $districtArr = [];
        foreach ($re as $k => $v) {
            if (in_array(3, explode(',', $v->function_arr)) || in_array(2, explode(',', $v->function_arr))) {
                $districtArr[] = $v->district_id;
            }
        }
        $adminList = [];
        if ($districtArr) {
            $adminList = \app\common\model\Shop::with('district')->where('district_id', 'in', $districtArr)
                ->limit($pageSize * $page, $pageSize)
                ->select();
        }
        return success($adminList);
    }


    /**
     * 商圈添加店铺
     * 0817 修正
     * 添加店铺进入商圈
     */
    public function shopAdd()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_id|商圈id' => 'require|number',
            'shop_id|店铺id'     => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断操作权限
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $param['district_id'])->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '3')) {
            return error('当前用户权限不足');
        }
        //判断店铺是否可以加入
        $shop_info = \app\common\model\Shop::find($param['shop_id']);
        if (!$shop_info) {
            return error('店铺信息异常');
        }
        if ($shop_info->district_id != 0) {
            if ($shop_info->district_id == $param['district_id']) {
                return error('该店铺已在商圈中,无需添加');
            }
            return error('该店铺已经在其他商圈中');
        }
        //判断店铺积分是否清零
        if ($shop_info->points_one != 0) {
            return error('该店铺积分未结算,暂时不能加入');
        }
        //加入商圈
        $shop_info->district_id = $param['district_id'];
        $shop_info->save();
        return success('添加成功');
    }

    /**
     * 商圈店铺删除
     */
    public function shopDelete()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //检查店铺状态
        $shopInfo = \app\common\model\Shop::find($param['shop_id']);
        if (!$shopInfo) {
            return error('店铺信息不存在');
        }
        if ($shopInfo->district_id == 0) {
            return error('当前店铺不在商圈中');
        }
        if ($shopInfo->points_one != 0) {
            return error('当前店铺存在未结算积分,暂不能离开商圈');
        }

        //判断操作权限
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $shopInfo->district_id)->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '3')) {
            return error('当前用户权限不足');
        }

        $shopInfo->district_id = 0;
        $shopInfo->save();
        return success('删除成功');
    }

    /**
     * 商圈--店铺结算
     * 0817  商圈管理员 有结算权限的角色
     * 可以通过 店铺发出去多少积分 以及获得多少积分  来结算
     * 积分大于0  商圈扣除多余积分  并线下给店铺支付等数量金额
     * 积分小于0  商圈满足积分到0  并线下收取店铺等数量金额
     */
    public function districtSettlement()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['shop_id'];
        //检查店铺状态
        $shopInfo = \app\common\model\Shop::find($shopId);
        if (!$shopInfo) {
            return error('店铺信息不存在');
        }
        if ($shopInfo->district_id == 0) {
            return error('当前店铺不在商圈中');
        }

        //判断操作权限
        $userId = $this->request->uid;
        $re     = BusinessDistrictAdmin::where('user_id', $userId)->where('district_id', $shopInfo->district_id)->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!strstr($re->function_arr, '2')) {
            return error('当前用户权限不足');
        }
        $num = $shopInfo->points_one;
        //统计不可结算积分
        $disableNum       = PointsLog::alias('pl')
            ->join('pm_order o', 'pl.relation_id = o.id', 'left')
            ->where('pl.shop_id', $shopId)
            ->where('pl.type', 2)
            ->where('pl.flag', 2)
            ->where('o.pay_status', 1)
            ->where('o.receive_time', 0)
            ->sum('pl.num');

        //最后需要结算的积分
        $num = $num - $disableNum;
        Db::startTrans();
        try {
            if ($num == 0) { //不需要结算
                return error('该店铺不需要结算');
            } elseif ($num < 0) {
                //需要补充店铺积分
                //商户增加积分记录
                PointsLog::create([
                    'form_user_id'   => $userId,
                    'user_id'        => 0,
                    'shop_id'        => $shopId,
                    'num'            => -$num,
                    'type'           => 4,
                    'flag'           => 3,
                    'relation_id'    => 0,
                    'relation_sheet' => 0,
                ]);
                $msg = '给店铺增加[' . -$num . ']积分';
            } else {  //需要扣除店铺积分
                //商户减少积分记录
                PointsLog::create([
                    'form_user_id'   => $userId,
                    'user_id'        => 0,
                    'shop_id'        => $shopId,
                    'num'            => $num,
                    'type'           => 5,
                    'flag'           => 4,
                    'relation_id'    => 0,
                    'relation_sheet' => 0,
                ]);
                $msg = '给店铺扣除[' . $num . ']积分';
            }
            $shopInfo->points_one = $shopInfo->points_one - $num;
            $shopInfo->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }

        return success(['num' => $num], $msg);
    }

    /**
     *  商圈店铺详情
     *  0817
     *  在进行结算的前一个页面来
     */
    public function districtShopDetail()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }

        $shopId = $param['shop_id'];

        $shop = \app\common\model\Shop::with('district')->find($shopId);
        if (!$shop) {
            return error('店铺信息异常');
        }
        //判断店铺 积分是否结算清楚
        //总共发出的积分
        $sendNum = PointsLog::where('shop_id', $shopId)
            ->where('type', 'in', [1, 5])
            ->sum('num');

        //总共收入积分
        $incomeNum = PointsLog::where(function ($query) use ($shopId) {
            $query
//                ->where(['shop_id' => $shopId, 'goods_shop_id' => 0])
                ->whereOr('goods_shop_id', $shopId);
        })
            ->where('type', 'in', [2, 4])
            ->sum('num');
        $num       = $incomeNum - $sendNum;
        if ($num != $shop->points_one) {
            $shop->points_one = $num;
            $shop->save();
        }
        //不可结算积分
        $num2       = PointsLog::alias('pl')
            ->join('pm_order o', 'pl.relation_id = o.id', 'left')
            ->where('pl.goods_shop_id', $shopId)
            ->where('pl.type', 2)
            ->where('pl.flag', 2)
            ->where('o.pay_status', 1)
            ->where('o.receive_time', 0)
            ->sum('pl.num');
        $shop->num2 = $num2;
        $shop->num3 = $num - $num2;
        $shop->points_one = $shop->num3;
        return success($shop);
    }

    /**
     * 店铺退出 商圈/连锁
     * 0824
     */
    public function shopExit()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //获取店铺id
        $shopId   = $param['shop_id'];
        $shopInfo = Shop::find($shopId);
        if (!$shopInfo) {
            return error('店铺信息异常');
        }
        if ($shopInfo->district_id == 0) {
            return error('当前店铺不在商圈/连锁内');
        }
        //获取用户id
        $userId = $this->request->uid;
        //获取用户权限
        $admin = ShopManage::where('shop_id', $shopId)->where('user_id', $userId)->find();
//        $admin = BusinessDistrictAdmin::where('district_id', $shopInfo->district_id)->where('user_id', $userId)->find();
        if (!$admin) {
            return error('当前用户没有操作权限');
        }
        if ($admin->role != 1) {//判断操作 只有超管可以操作退出商圈或者连锁
            return error('当前用户操作权限不足');
        }
        //判断店铺 积分是否结算清楚
        //总共发出的积分
        $sendNum = PointsLog::where('shop_id', $shopId)
            ->where('type', 'in', [1, 5])
            ->sum('num');

        //总共收入积分
        $incomeNum = PointsLog::where('shop_id', $shopId)
            ->where('type', 'in', [2, 4])
            ->sum('num');
        $num       = $incomeNum - $sendNum;
        if ($num != 0) {
            return error('当前店铺积分未完成清算,不能退出商圈/连锁');
        }
        //退出操作
        $shopInfo->district_id = 0;
        $shopInfo->save();
        return success([], '退出商圈/连锁成功');
    }

    /**
     *
     *商圈管理 -- 商圈首页 展示信息
     * 0824
     */
    public function districtInfo()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_id|商圈id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $districtId = $param['district_id'];

        //获取商圈信息
        $out = BusinessDistrict::find($districtId);
        return success($out);
    }

    /**
     * 商圈信息修改
     * 0824
     */
    public function districtInfoUpdate()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'district_id|商圈id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $districtId = $param['district_id'];
        //获取用户信息
        $userId = $this->request->uid;
        //判断用户权限
        $admin = BusinessDistrictAdmin::where('district_id', $districtId)
            ->where('user_id', $userId)
            ->find();
        if (!$admin) {
            return error('当前用户没有权限');
        }
        if (!strstr($admin->function_arr, '1')) {
            return error('当前用户权限不足');
        }
        //获取商圈信息
        $district        = BusinessDistrict::find($districtId);
        $district->tip   = input('tip', '');
        $district->image = input('image', '');
        $district->logo  = input('logo', '');
        $district->title = input('title', '');
        $district->save();
        return success([]);
    }
}